package com.ww.springboot.boot.java8.completablefuture;

import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * todo
 *
 * @author wanwei
 * @since 2021-04-28 17:17
 */
public class CompletableFutureDemo {

    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2, Runtime.getRuntime().availableProcessors() * 2,
            10, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new CustomizableThreadFactory("platformStore-thread-pool"));


    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        List<Integer> integers = IntStream.range(0, 10).boxed().collect(Collectors.toList());
        System.out.println(integers);

        System.out.println("开始" + System.currentTimeMillis());
        List<Integer> integersNew = new ArrayList<>();

        CompletableFuture[] completableFutures = integers.stream().map(i ->
                CompletableFuture.supplyAsync(() -> {
                    try {
                        TimeUnit.SECONDS.sleep(i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //Long.valueOf("a");
                    return i + 1;
                }, threadPoolExecutor)
                        .whenCompleteAsync((j, e) -> integersNew.add(j))
        ).toArray(CompletableFuture[]::new);

        //join 主线程等待所有线程执行完再继续执行
        //CompletableFuture.allOf(completableFutures).join();
//        System.out.println("第二步:" + System.currentTimeMillis());
//        CompletableFuture.allOf(completableFutures).join();
//        System.out.println("第三步:" + System.currentTimeMillis());
        try{
            CompletableFuture.allOf(completableFutures).get(1, TimeUnit.SECONDS);
        }catch (TimeoutException e){
            System.out.println("超时！！！！！！！！！！！！！");
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }


        System.out.println(integersNew);
        System.out.println("结束" + System.currentTimeMillis());

    }
}
